from flask import Blueprint, request, jsonify
from app import db, jwt
from app.models.blood_test import BloodTest
from flask_jwt_extended import jwt_required, get_jwt_identity

bp = Blueprint('blood_test', __name__, url_prefix='/api/blood-test')

@bp.route('', methods=['POST'])
@jwt_required()
def create_blood_test():
    """创建血液检测记录"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        blood_test = BloodTest(
            user_id=user_id,
            fasting_blood_sugar=data.get('fasting_blood_sugar'),
            postprandial_blood_sugar=data.get('postprandial_blood_sugar'),
            hba1c=data.get('hba1c'),
            total_cholesterol=data.get('total_cholesterol'),
            triglycerides=data.get('triglycerides'),
            hdl_cholesterol=data.get('hdl_cholesterol'),
            ldl_cholesterol=data.get('ldl_cholesterol'),
            alt=data.get('alt'),
            ast=data.get('ast')
        )
        
        db.session.add(blood_test)
        db.session.commit()
        
        return jsonify({
            'message': '血液检测记录创建成功',
            'data': blood_test.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('', methods=['GET'])
@jwt_required()
def get_blood_tests():
    """获取用户的全部血液检测记录"""
    try:
        user_id = get_jwt_identity()
        records = BloodTest.query.filter_by(user_id=user_id).order_by(BloodTest.test_date.desc()).all()
        
        return jsonify({
            'data': [record.to_dict() for record in records]
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['GET'])
@jwt_required()
def get_blood_test_by_id(record_id):
    """获取特定血液检测记录"""
    try:
        user_id = get_jwt_identity()
        record = BloodTest.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
            
        return jsonify({
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['PUT'])
@jwt_required()
def update_blood_test(record_id):
    """更新血液检测记录"""
    try:
        user_id = get_jwt_identity()
        record = BloodTest.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        data = request.get_json()
        
        # 更新字段
        update_fields = [
            'fasting_blood_sugar', 'postprandial_blood_sugar', 'hba1c',
            'total_cholesterol', 'triglycerides', 'hdl_cholesterol', 
            'ldl_cholesterol', 'alt', 'ast'
        ]
        
        for field in update_fields:
            if field in data:
                setattr(record, field, data[field])
        
        db.session.commit()
        
        return jsonify({
            'message': '血液检测记录更新成功',
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['DELETE'])
@jwt_required()
def delete_blood_test(record_id):
    """删除血液检测记录"""
    try:
        user_id = get_jwt_identity()
        record = BloodTest.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        db.session.delete(record)
        db.session.commit()
        
        return jsonify({
            'message': '血液检测记录删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500